import { ElNotification } from "element-plus";
import { feature } from "../utils/axios-utils";

/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
export const useDownload = async (
  api: (param: any) => Promise<any>,
  tempName: string,
  params: any = {},
  isNotify: boolean = true,
  fileType: string = ".xlsx"
) => {
  if (isNotify) {
    ElNotification({
      title: "温馨提示",
      message: "如果数据庞大会导致下载缓慢哦，请您耐心等待！",
      type: "info",
      duration: 3000
    });
  }
  try {
    const [err, res] = await feature(api(params));
    if (err) {
      return err.message;
    }
    //解析stream中的文件名
    const contentDisposition = res.headers["content-disposition"];
    const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/g;
    const matches = contentDisposition.match(filenameRegex);
    let fileName = "";
    if (matches && matches.length > 0) {
      const filenameValue = matches[1];
      fileName = filenameValue.split("=")[1].trim();
      fileName = decodeURIComponent(fileName.replace("UTF-8''", ""));
    }
    const name = fileName ?? `${tempName}${fileType}`;
    const blob = new Blob([res.data]);
    // 兼容 edge 不支持 createObjectURL 方法
    if ("msSaveOrOpenBlob" in navigator) return window.navigator.msSaveOrOpenBlob(blob, name);
    const blobUrl = window.URL.createObjectURL(blob);
    const exportFile = document.createElement("a");
    exportFile.style.display = "none";
    exportFile.download = name;
    exportFile.href = blobUrl;
    document.body.appendChild(exportFile);
    exportFile.click();
    // 去除下载对 url 的影响
    document.body.removeChild(exportFile);
    window.URL.revokeObjectURL(blobUrl);
    return name;
  } catch (error: any) {
    return error;
  }
};
